package com.canbot.u05.activity.guide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.guide.MapInfo;
import com.canbot.u05.bean.guide.MapMsgBean;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.socket.StringMsgBean;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 *
 * @author zmp
 * @date 2017/5/17
 * 导览设置选择地图界面
 */

public class GuideMapListActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private long mapID = -1;

        private long currentID = -1;

        private MyMapListAdapter mapListAdapter;

        private ToastTools toastTools;

        public static final int GUIDE_CODE_Q = 1001;

        private boolean isBuildMap;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.guide_map_list_activity);
                ListView mListView = (ListView) findViewById(R.id.guide_maplist_lv);
                findViewById(R.id.guide_maplist_ok).setOnClickListener(this);
                findViewById(R.id.main_iv_back).setOnClickListener(this);
                findViewById(R.id.guide_buid_map_bt).setOnClickListener(this);
                mapListAdapter = new MyMapListAdapter();
                mListView.setAdapter(mapListAdapter);
                mListView.setOnItemClickListener(itemClickListener);
                toastTools = ToastTools.newInstance(GuideMapListActivity.this);
                initData();
        }

        private void initData() {
                isBuildMap = false;
                if (GuideActivity.mMapInfo == null) {
                        currentID = -1;
                } else {
                        currentID = GuideActivity.mMapInfo.get_id();
                }
                mapID = currentID;
                showLoadDialog();
                getMapList();
        }

        @Override
        protected void onResume() {
                super.onResume();
                EventBus.getDefault().register(this);
                if (isBuildMap) {
                        initData();
                }
        }

        @Override
        protected void onPause() {
                super.onPause();
                EventBus.getDefault().unregister(this);
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
        }

        /**
         * 消息发布者位置
         * ReceiveData
         * mHandler
         * case MsgType.MOBILE_PAD_MAP_TASK:
         *
         * @param bean
         */
        @Subscribe(threadMode = ThreadMode.MAIN)
        public void onMapEvent(StringMsgBean bean) {
                if (bean.getMsgType() == MsgType.MOBILE_PAD_MAP_TASK) {
                        String msgData = bean.getMsgData();
                        if (!TextUtils.isEmpty(msgData)) {
                                loadDialog.dismiss();
                                MapMsgBean mapMsgBean = new Gson().fromJson(msgData, MapMsgBean.class);
                                if (MapMsgBean.MOBILE_LOAD_MAP == mapMsgBean.getMsgType()) {
                                        if (mapMsgBean.isSuccess()) {
                                                setResult(RESULT_OK);
                                                finish();
                                        } else {
                                                if ("success".equals(mapMsgBean.getMsgData())) {
                                                        startForResultActivity(GuideMapRestoreActivity.class, GUIDE_CODE_Q);
                                                } else {
                                                        toastTools.showText("地图加载失败！");
                                                }
                                        }
                                }
                        }
                }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == GUIDE_CODE_Q && resultCode == RESULT_OK) {
                        setResult(RESULT_OK);
                        finish();
                }
        }

        AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mapID = mapList.get(position).get_id();
                        mapListAdapter.notifyDataSetChanged();
                }
        };

        List<MapInfo> mapList = new ArrayList<>();

        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                        case R.id.guide_maplist_ok:
                                if (mapList == null || mapList.size() == 0) {
                                        startForResultActivity(GuideMapRestoreActivity.class, GUIDE_CODE_Q);
                                        return;
                                }
                                if (mapID == -1) {
                                        toastTools.showText("请选择要加载的地图！");
                                        break;
                                }
                                if (mapID == currentID) {
                                        startForResultActivity(GuideMapRestoreActivity.class, GUIDE_CODE_Q);
                                        return;
                                }
                                showLoadDialog();
                                loadMapInfoById(mapID);
                                break;
                        case R.id.main_iv_back:
                                setResult(2);
                                finish();
                                break;
                        case R.id.guide_buid_map_bt:
                                showLoadDialog();
                                initMapSocket();
                                break;
                        case R.id.guide_dialog_hint_sure:
                                noMapDialog.dismiss();
                                showLoadDialog();
                                initMapSocket();
                                break;
                        case R.id.guide_dialog_hint_move:
                                noMapDialog.dismiss();
                                setResult(RESULT_CANCELED);
                                finish();
                                break;
                        default:
                }
        }

        private void initMapSocket() {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 10 + "");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                loadDialog.dismiss();
                                Log.e("TTS2Voice", result);
                                Intent intent = GuideMapListActivity.this.getPackageManager()
                                        .getLaunchIntentForPackage("com.canbot.slamtec.maptools.u05");
                                if (intent != null) {
                                        isBuildMap = true;
                                        startOtherActivity(intent, false);
                                } else {
                                        toastTools.showText("此功能尚未开放，敬请期待！");
                                }
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText("网络异常，请确认Wifi！");
                        }
                });
        }

        class MyMapListAdapter extends BaseAdapter {

                MyMapListAdapter() {
                }

                @Override
                public int getCount() {
                        return mapList == null || mapList.size() == 0 ? 0 : mapList.size();
                }

                @Override
                public Object getItem(int position) {
                        return mapList.get(position);
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        Holder holder;
                        if (convertView == null) {
                                convertView = View.inflate(GuideMapListActivity.this, R.layout.guide_maplist_item, null);
                                holder = new Holder(convertView);
                                convertView.setTag(holder);
                        }
                        holder = (Holder) convertView.getTag();
                        MapInfo mapInfo = mapList.get(position);
                        holder.textView.setText(mapInfo.getMapName());
                        holder.imageView.setSelected(mapInfo.get_id() == mapID);
                        return convertView;
                }
        }

        class Holder {

                private TextView textView;

                private ImageView imageView;

                public Holder(View convertView) {
                        textView = (TextView) convertView.findViewById(R.id.guide_maplist_item_tv);
                        imageView = (ImageView) convertView.findViewById(R.id.guide_maplist_item_bt);
                }
        }

        private void getMapList() {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 1 + "");
                //        hashMap.put("data", data);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("TTS2Voice", result);
                                loadDialog.dismiss();
                                if (TextUtils.isEmpty(result) || "success".equals(result)) {
                                        toastTools.showText("当前暂无地图数据！");
                                        MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(9));
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        showHintDialog();
                                                }
                                        });

                                        return;
                                }
                                Type type = new TypeToken<ArrayList<MapInfo>>() {
                                }.getType();
                                mapList = new Gson().fromJson(result, type);
                                if (mapList == null || mapList.size() == 0) {
                                        toastTools.showText("当前暂无地图数据！");
                                        MapVoiceAndEyes.playMapVoiceAndEyes(MapVoiceAndEyes.voiceEyesList.get(9));
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        showHintDialog();
                                                }
                                        });
                                        return;
                                }
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                mapListAdapter.notifyDataSetChanged();
                                        }
                                });
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText("服务器异常");
                                setResult(RESULT_CANCELED);
                                finish();
                        }
                });
        }

        private void loadMapInfoById(long mapID) {
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 6 + "");
                hashMap.put("data", mapID);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                loadDialog.setCancelable(true);
                                Log.e("TTS2Voice", result);
                        }

                        @Override
                        public void onFailure() {
                                loadDialog.dismiss();
                                toastTools.showText("服务器异常");
                        }
                });
        }

        private Dialog loadDialog;

        private void showLoadDialog() {
                if (loadDialog == null) {
                        loadDialog = new Dialog(this, R.style.MyDialogStyle);
                        loadDialog.setContentView(R.layout.guide_dialog_load);
                        loadDialog.setCancelable(false);
                }
                StatusBarUtil.hideVirtualKey(loadDialog);
                loadDialog.show();
        }

        private Dialog noMapDialog;

        private void showHintDialog() {
                if (noMapDialog == null) {
                        noMapDialog = new Dialog(this, R.style.MyDialogStyle);
                        noMapDialog.setContentView(R.layout.guide_dialog_hint);
                        Button sure = (Button) noMapDialog
                                .findViewById(R.id.guide_dialog_hint_sure);
                        sure.setText("前往定制");
                        sure.setOnClickListener(this);
                        Button move = ((Button) noMapDialog
                                .findViewById(R.id.guide_dialog_hint_move));
                        move.setText("取消");
                        move.setOnClickListener(this);
                        TextView textView = (TextView) noMapDialog.findViewById(R.id.guide_dialog_tv);
                        textView.setText("未检测到当前环境可用的地图，请先建立地图！");
                }
                StatusBarUtil.hideVirtualKey(noMapDialog);
                noMapDialog.show();
        }
}


